<?php
class CategoryController extends Controller{
	private $db;
	private $category;
	//构造函数
	public function __init(){
		$this->db=K('Category');
		//获得所有栏目
		$this->category=$this->db->getlist();
	}
	//显示栏目列表
	public function index(){
		$this->assign('data',$this->category);
		$this->display();
	}
	//添加栏目
	public function add(){
		if(IS_POST){
			if($this->db->addCategory()){
				$this->success('操作成功','index');
			}else{
				$this->error($this->db->error);
			}
		}else{
			$this->assign('category',$this->category);
			$this->display();
		}
	}
	//修改栏目
	public function edit(){
		if(IS_POST){
			if($this->db->editCategory()){
				$this->success('修改成功','index');
			}else{
				$this->error($this->db->error);
			}
		}else{ //Q 函数超全数组,Q('变量名',变量默认值,'变量处理方式');
			$cid =Q('get.cid',0,'intval');
			//取当前编辑栏目数据
			$field= $this->db->find($cid);
			// p($field);exit;
			$this->assign('field',$field);
			$category = $this->category;
			 // p($category);exit;
			foreach($category as $id=>$cat){
				//当前父栏目设置 selected属性
				$category[$id]['selected']=$cat['cid']==$field['pid']?" selected='' ":'';			
				//子栏目设置disabled 自身也不能选择
				// Data::isChild() 判断是否为子栏目
				// 数组,子id,父栏目id
				$category[$id]['disabled']=Data::isChild($category,$cat['cid'],$field['cid']) || $cat['cid']==$field['cid']?
					" disabled='' ":'';
			}
			$this->assign('category',$category);
			$this->display();
		}
	}

	
	//删除栏目
	public function del(){
		$cid =Q('cid',0,'intval');//$_REQUEST  cookie post  get
		if($this->db->delCategory($cid)){
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
	}
}